package com.ruoyi.disk.util;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ruoyi.common.config.RuoYiConfig;
import java.util.UUID;

/**
 * 备份目录工具类
 * 用于自动创建和管理备份目录结构
 */
public class BackupDirectoryUtil {
    
    private static final Logger log = LoggerFactory.getLogger(BackupDirectoryUtil.class);
    
    /**
     * 确保备份目录存在，如果不存在则创建
     * @param userId 用户ID
     * @param backupId 备份ID
     * @return 是否成功创建或确认目录存在
     */
    public static boolean ensureBackupDirectoryExists(Long userId, String backupId) {
        try {
            // 获取备份根目录
            String profilePath = RuoYiConfig.getProfile();
            String backupBaseDir = profilePath + "/backup/" + userId + "/";
            String backupDir = backupBaseDir + backupId + "/";
            
            log.info("检查备份目录是否存在: {}", backupDir);
            
            // 创建备份目录
            File backupDirFile = new File(backupDir);
            if (!backupDirFile.exists()) {
                log.info("备份目录不存在，正在创建: {}", backupDir);
                boolean created = backupDirFile.mkdirs();
                if (!created) {
                    log.error("无法创建备份目录: {}", backupDir);
                    return false;
                }
                
                // 创建一个测试文件
                File testFile = new File(backupDir + "test-file.txt");
                FileUtils.writeStringToFile(testFile, "这是一个自动创建的测试备份文件", "UTF-8");
                log.info("已创建测试文件: {}", testFile.getAbsolutePath());
                
                // 创建元数据文件
                String metadataStr = "{\"files\":[],\"backupId\":\"" + backupId + "\",\"userId\":" + userId + 
                                    ",\"backupTime\":\"" + new Date() + "\",\"totalFiles\":1,\"totalSize\":0}";
                File metadataFile = new File(backupDir + "metadata.json");
                FileUtils.writeStringToFile(metadataFile, metadataStr, "UTF-8");
                log.info("已创建元数据文件: {}", metadataFile.getAbsolutePath());
                
                // 更新索引文件
                updateBackupIndex(userId, backupId);
            }
            
            return true;
        } catch (Exception e) {
            log.error("确保备份目录存在时发生错误", e);
            return false;
        }
    }
    
    /**
     * 更新备份索引文件
     * @param userId 用户ID
     * @param backupId 备份ID
     */
    private static void updateBackupIndex(Long userId, String backupId) {
        try {
            String profilePath = RuoYiConfig.getProfile();
            String backupBaseDir = profilePath + "/backup/" + userId + "/";
            File indexFile = new File(backupBaseDir + "index.json");
            
            String indexContent;
            if (indexFile.exists()) {
                // 读取现有索引
                indexContent = FileUtils.readFileToString(indexFile, "UTF-8");
                // 移除最后的 "]"
                if (indexContent.endsWith("]")) {
                    indexContent = indexContent.substring(0, indexContent.length() - 1);
                    // 如果不是空数组，添加逗号
                    if (!indexContent.trim().equals("[")) {
                        indexContent += ",";
                    }
                } else if (indexContent.trim().isEmpty()) {
                    // 如果是空文件，创建新的数组
                    indexContent = "[";
                }
            } else {
                // 创建新索引文件
                indexContent = "[";
            }
            
            // 添加新的备份记录
            String newBackupEntry = "{\"backupId\":\"" + backupId + "\",\"backupTime\":\"" + 
                                   new Date() + "\",\"fileCount\":1,\"totalSize\":0}]";
            indexContent += newBackupEntry;
            
            // 写入索引文件
            FileUtils.writeStringToFile(indexFile, indexContent, "UTF-8");
            log.info("已更新索引文件: {}", indexFile.getAbsolutePath());
        } catch (IOException e) {
            log.error("更新备份索引文件时发生错误", e);
        }
    }
    
    /**
     * 创建新的备份目录
     * @param userId 用户ID
     * @return 新创建的备份ID
     */
    public static String createNewBackupDirectory(Long userId) {
        String backupId = "index-" + UUID.randomUUID().toString().substring(0, 12);
        boolean created = ensureBackupDirectoryExists(userId, backupId);
        return created ? backupId : null;
    }
} 